// @flow
import React from 'react'
import { Tabs, Table, DatePicker, Select, Spin } from 'antd'
import DynamicLine from 'components/DynamicLine'
import ScatterHistoryLine from 'components/ScatterHistoryLine'
import moment from 'moment'
import SelectIndicator from 'components/SelectIndicator'
import { changeHistoryChartCond,
  changeDynamicChartCond, changeDynamicDateCond } from 'store/modules/deviceFileCondition'
import styles from './ConditionChart.css'
import classname from 'classnames/bind'
import { connect } from 'react-redux'
import universalFetch, { handleFetchError, LoginFetch } from 'store/modules/fetch'
import HistoryLine from 'components/HistoryLine'
import R from 'ramda'
const TabPane = Tabs.TabPane
const Option = Select.Option
const { RangePicker } = DatePicker
const cx = classname.bind(styles)
const columns = [
  { title: '事件名称',
    dataIndex: 'eventName' },
  { title: '事件类型',
    dataIndex: 'eventType'
  },
  { title: '开始时间',
    dataIndex: 'startTime'
  },
  { title: '结束时间',
    dataIndex: 'endTime'
  },
  { title: '负责人',
    dataIndex: 'owner'
  },
  { title: '处理状态',
    dataIndex: 'status'
  },
  { title: '事件描述',
    dataIndex: 'detail'
  }
]

type Props = {
  deviceCard: Object,
  location: Object,
  deviceFileCondition: Object,
  changeHistoryChartCond: Function,
  changeDynamicChartCond: Function,
  changeDynamicDateCond: Function
}

type State = {
  chartData: Array<any>,
  dynamicTable: Array<any>,
  historyTable: Array<any>,
  historyFrom: any,
  historyTo: any,
  xData: Array<any>,
  dynamicIndicator: Array<string>,
  groupId: string,
  deviceData: Object,
  historyDates: Array<moment>,
  dynamicDates: Array<moment>,
  chartView: string,
  scatterData: Array<Object>,
  scatterXLabel: string,
  defaultActiveKey: string,
  loading: boolean,
  defaultTime: Array<any>,
  changeXData: Array<string>
}

class Condition extends React.Component {
  props: Props
  state: State
  refreshHistoryChartData: Function
  updataTable: Function
  historyTable: Function
  plotBands: Function
  columns1: Array<Object>
  changeHistoryCond: Function
  changeDynamicCond: Function
  historyTimeCondOnOk: Function
  changeHistoryTimeCond: Function
  changeDynamicDate: Function
  dynamicDateCondOnOk: Function
  changeChartView: Function
  changeScatter: Function
  initialDraw: Function
  tabOnchange: Function
  constructor (props: Object) {
    super(props)
    const component = this
    this.columns1 = [
      { title: '事件名称',
        dataIndex: 'eventName',
        render: (text, record, index) => (
          <a onClick={
            function () {
              component.plotBands(record)
            }}>
            {text}
          </a>
        )
      },
      { title: '事件类型',
        dataIndex: 'eventType'
      },
      { title: '开始时间',
        dataIndex: 'startTime'
      },
      { title: '结束时间',
        dataIndex: 'endTime'
      },
      { title: '负责人',
        dataIndex: 'owner'
      },
      { title: '处理状态',
        dataIndex: 'status'
      },
      { title: '事件描述',
        dataIndex: 'detail'
      }
    ]

    this.state = {
      chartData: [],
      dynamicTable: [],
      historyTable: [],
      xData: [],
      dynamicIndicator: [''],
      groupId: this.props.deviceCard.groupId,
      historyFrom: null,
      historyTo: null,
      deviceData: this.props.deviceCard.deviceData,
      historyDates: [],
      dynamicDates: [],
      scatterData: [],
      chartView: 'single',
      scatterXLabel: 'time',
      defaultActiveKey: 'dynamicTab',
      loading: false,
      defaultTime: [moment(0, 'HH'), moment()],
      changeXData: []
    }

    this.refreshHistoryChartData = this.refreshHistoryChartData.bind(this)
    this.updataTable = this.updataTable.bind(this)
    this.historyTable = this.historyTable.bind(this)
    this.plotBands = this.plotBands.bind(this)
    this.changeHistoryCond = this.changeHistoryCond.bind(this)
    this.changeDynamicCond = this.changeDynamicCond.bind(this)
    this.historyTimeCondOnOk = this.historyTimeCondOnOk.bind(this)
    this.changeHistoryTimeCond = this.changeHistoryTimeCond.bind(this)
    this.changeDynamicDate = this.changeDynamicDate.bind(this)
    this.dynamicDateCondOnOk = this.dynamicDateCondOnOk.bind(this)
    this.changeChartView = this.changeChartView.bind(this)
    this.changeScatter = this.changeScatter.bind(this)
    this.initialDraw = this.initialDraw.bind(this)
    this.tabOnchange = this.tabOnchange.bind(this)
  }

  changeChartView (value) {
    this.setState({
      chartView: value
    })
  }
/**
 * 历史表格数据&&历史表格
 * @return {[type]} [description]
 */
  historyTable () {
    const { historyCond } = this.props.deviceFileCondition
    const { startTime, endTime } = historyCond
    universalFetch(`${__SERVICE_API__}device/devices/${this.state.deviceData.id}/events?orderBy=update_time%20desc` +
      `&startDate=${startTime.toISOString()}&endDate=${endTime.toISOString()}`
    )
      .then((res) => res.json())
      .then((json) => {
        const result = json.result.eventList
        this.setState({
          historyTable:result.map((data, i) => {
            data['startTime'] = moment(data.startTime, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD HH:mm:ss')
            data['endTime'] = moment(data.endTime, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD HH:mm:ss')
            data['key'] = i
            return data
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  /**
   * 历史折线数据
   * @return {[type]} [description]
   */
  refreshHistoryChartData (monitors, keyNameValue, start, end) {
    const deviceNo = this.state.deviceData.deviceNo.split('_')
    let channelNames = []
    const res = monitors.map((monitorsItem, i) => {
      channelNames = monitorsItem.channelNames
      const postBody = JSON.stringify({
        fieldGroup: monitorsItem.En,
        fields: monitorsItem.key,
        coValueFilter: {
          idFieldFilter: {
            // machinename: { '$eq': String(this.state.deviceData.deviceNo) },
            // keyname: { '$eq': keyNameValue },
            factory_id: { '$eq': String(deviceNo[0]) },
            equipment_id: { '$eq': String(deviceNo[1]) },
            machine_id: { '$eq': String(deviceNo[2]) },
            datatype: { '$eq': '1' },
            '$or': monitorsItem.channelIds.map((d, i) => {
              return { 'channel_id': { '$eq': String(d) } }
            })
          }
          // nonIdFieldFilter: {
          //   '$or': channelIds.map((d, i) => {
          //     return { 'channel_id': { '$eq': d } }
          //   })
          // }
        },
        timeRange: {
          start: start,
          end: end
        },
        valueFilters: [
            { '$default': { '$or': [{ '$gt': -1000000 }] } }
        ],
        size: 10000,
        page: 1
      })
      return LoginFetch(`${__KMX_API__}data-streams`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: postBody
      }).then((res) => res.json())
    })
    Promise.all(res).then((jsons) => {
      let results = []
      jsons.map((d) => {
        results.push(...d.results)
      })
      this.setState({
        loading: false
      })
      let monitorNames = []
      monitors.map((d) => {
        monitorNames.push(...d.keyName)
      })
      const cloneResults = R.clone(results)
      if (results && results.length > 0) {
        this.setState({
          chartData: results.map((data, index) => {
            const channelArray = channelNames.filter((dd) => dd.id === data.compoundId.channel_id)
            const name = monitorNames.filter((dd) => dd.key === data.field)[0].name
            data['name'] = name + '__' + channelArray[0].name
            data['type'] = 'line'
            data['data'] = data.streams.map((d, i) => {
              return d
            })
            return data
          }),
          scatterData: cloneResults.map((data, index) => {
            const channelArray = channelNames.filter((dd) => dd.id === data.compoundId.channel_id)
            const name = monitorNames.filter((dd) => dd.key === data.field)[0].name
            data['name'] = name + '__' + channelArray[0].name
            data['type'] = 'scatter'
            data['data'] = data.streams.map((d, i) => {
              return d
            })
            return data
          }),
          changeXData: cloneResults.map((data, index) => {
            const channelArray = channelNames.filter((dd) => dd.id === data.compoundId.channel_id)
            const name = monitorNames.filter((dd) => dd.key === data.field)[0].name
            return name + '__' + channelArray[0].name
          }),
          xData: results[0].streams.map((d, i) => {
            return d[0]
          })
        })
      }
    })
    .catch(() => {
      this.setState({
        loading: false
      })
    })
  }

  changeScatter (xlabel) {
    this.setState({
      scatterXLabel: xlabel
    })
    // const { scatterData } = this.state
  }

  updataTable () {
    this.historyTable()
  }

  // 选中某段日期
  plotBands (record) {
    this.setState({
      historyFrom: moment(record.startTime).valueOf(),
      historyTo: moment(record.endTime).valueOf()
    })
  }

  /**
   * 改变历史图表选择指标条件
   * @param  {[type]} monitors [description]
   * @return {[type]}          [description]
   */
  changeHistoryCond (monitors, keyNameValue) {
    this.setState({
      loading: true
    })
    const { historyCond } = this.props.deviceFileCondition
    this.props.changeHistoryChartCond(Object.assign({}, historyCond, {
      monitors: monitors,
      keyNameValue: keyNameValue
    }))
  }

  changeDynamicCond (monitors, keyNameValue) {
    // this.props.changeDynamicChartCond(monitors)
    this.props.changeDynamicChartCond({
      monitors: monitors,
      keyNameValue: keyNameValue
    })
  }

  /**
    * 改变历史图表时间选择条件
    * @return {[type]} [description]
    */
  changeHistoryTimeCond (dates, dateStrings) {
    this.setState({
      loading: true,
      historyDates: dates
    })
  }

   /**
    * 历史时间条件点击确定回调
    * @return {[type]} [description]
    */
  historyTimeCondOnOk () {
    const { historyCond } = this.props.deviceFileCondition
    this.props.changeHistoryChartCond(Object.assign({}, historyCond, {
      startTime: this.state.historyDates[0],
      endTime: this.state.historyDates[1]
    }))
    // const components = this
    // setTimeout(() => {
    //   components.historyTable()
    // }, 100)
  }

  initialDraw (props) {
    const { historyCond } = props.deviceFileCondition
    if (historyCond && historyCond.monitors && historyCond.monitors.length === 0) {
      return
    }

    // let monitorNames = []
    // historyCond.monitors.map((d) => {
    //   monitorNames.push(...d.keyName)
    // })
    // this.setState({
    //   chartData: monitorNames.map((data, index) => {
    //     return {
    //       name: data,
    //       type: 'line',
    //       data: []
    //     }
    //   })
    // })

    this.refreshHistoryChartData(
     historyCond.monitors,
     historyCond.keyNameValue,
     historyCond.startTime.format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
     historyCond.endTime.format('YYYY-MM-DDTHH:mm:ss.SSSZ')
    )
  }

  componentWillMount () {
    // const state = this.props.location.state
    // if (state) {
    //   if (state.hasOwnProperty('defaultActiveKey')) {
    //     this.setState({
    //       defaultActiveKey: state.defaultActiveKey
    //     })
    //   }
    //   if (state.hasOwnProperty('dynamicIndicator')) {
    //     let Ind = []
    //     Ind.push(state.dynamicIndicator)
    //     this.setState({
    //       dynamicIndicator: Ind
    //     })
    //   }
    // }
    // 将历史的默认时间传到store中
    const { historyCond } = this.props.deviceFileCondition
    this.props.changeHistoryChartCond(Object.assign({}, historyCond, {
      startTime: this.state.defaultTime[0],
      endTime: this.state.defaultTime[1]
    }))

    // this.historyTable()
    // this.initialDraw(this.props)
  }

  componentWillReceiveProps (nextProps) {
    const { defaultActiveKey } = this.state
    if (defaultActiveKey === 'historyTab') {
      this.initialDraw(nextProps)
    }
    // if (defaultActiveKey === 'historyTab' &&
    // !R.equals(nextProps.deviceFileCondition, this.props.deviceFileCondition)) {
    //   this.initialDraw(nextProps)
    // }
  }

  changeDynamicDate (dates) {
    this.setState({
      dynamicDates: dates
    })
  }

  dynamicDateCondOnOk () {
    const { dynamicDate } = this.props.deviceFileCondition
    this.props.changeDynamicDateCond(Object.assign({}, dynamicDate, {
      startTime: this.state.dynamicDates[0],
      endTime: this.state.dynamicDates[1]
    }))
  }
  tabOnchange (activeKey) {
    this.setState({
      defaultActiveKey: activeKey
    })
  }

  render () {
    // const { historyCond, dynamicDate } = this.props.deviceFileCondition
    const { chartData, chartView, scatterXLabel, loading, defaultTime, changeXData } = this.state
    const chartDataLen = chartData.length
    const scatterSettingStyle = cx({
      'scatter-settings': true,
      'animated': true,
      'fadeInRight': chartView === 'scatter',
      // 'fadeInLeft': chartView !== 'scatter',
      'scatter-hide': chartView !== 'scatter'
    })
    const { keyName } = this.state.deviceData
    // let monitorKeys = []
    // historyCond.monitors.map((d) => {
    //   monitorKeys.push(...d.key)
    // })
    return (
      <div className={styles['main']}>
        <Tabs defaultActiveKey={this.state.defaultActiveKey} onChange={this.tabOnchange}>
          <TabPane tab='实时数据' key='dynamicTab'>
            <div>
              {
              // <Select defaultValue='单图显示' style={{ width: 120, marginLeft:8 }}>
              //   <Option value='单图显示'>单图显示</Option>
              //   <Option value='多图显示'>多图显示</Option>
              //   <Option value='散点显示'>散点显示</Option>
              // </Select>
              // <RangePicker
              //   showTime
              //   format='YYYY-MM-DD HH:mm:ss'
              //   defaultValue={[dynamicDate.startTime, dynamicDate.endTime]}
              //   onOk={() => this.dynamicDateCondOnOk()}
              //   onChange={this.changeDynamicDate}
              //   style={{ marginLeft: 8 }}
              // />
              }
              <SelectIndicator
                dynamicIndicator={this.state.dynamicIndicator}
                keyName={keyName.split(',')}
                callback={this.changeDynamicCond}
                />
            </div>
            <div className={styles['top']}>
              <DynamicLine
                dynamicIndicator={this.state.dynamicIndicator}
                // xData={this.state.xData}
                // chartData={this.state.chartData}
                />
            </div>
          </TabPane>
          <TabPane tab='历史数据' key='historyTab'>
            <div>
              <Select defaultValue='single'
                onChange={this.changeChartView}
                >
                <Option value='single'>单图显示</Option>
                {
                  chartDataLen > 1
                  ? <Option value='more'>多图显示</Option>
                  : <Option value='more' disabled>多图显示</Option>
                }
                <Option value='scatter'>散点显示</Option>
              </Select>
              <RangePicker
                showTime
                format='YYYY-MM-DD HH:mm:ss'
                // defaultValue={[historyCond.startTime, historyCond.endTime]}
                defaultValue={defaultTime}
                onOk={() => this.historyTimeCondOnOk()}
                onChange={this.changeHistoryTimeCond}
                style={{ marginLeft: 8 }}
              />
              <SelectIndicator
                dynamicIndicator={this.state.dynamicIndicator}
                keyName={keyName.split(',')}
                callback={this.changeHistoryCond}
              />
              <div className={scatterSettingStyle}>
                <span className={styles['scatter-label']}>切换为横轴的点:</span>
                <Select
                  showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }}
                  style={{ width: 120 }}
                  defaultValue='time'
                  onChange={this.changeScatter}
                  >
                  <Option value='time'>
                    时间
                  </Option>
                  {
                    changeXData.length > 1
                    ? changeXData.map((item, i) => {
                      return <Option key={i} value={item}>
                        {item}
                      </Option>
                    })
                    : []
                  }
                </Select>
              </div>
            </div>
            {
              chartView === 'single'
              ? <div className={styles['top']}>
                <Spin spinning={loading} tip='加载中...'>
                  <HistoryLine
                    xData={this.state.xData}
                    chartData={this.state.chartData}
                    historyFrom={this.state.historyFrom}
                    historyTo={this.state.historyTo}
                    updateEvents={this.updataTable}
                  />
                </Spin>
              </div>
              : false
            }
            {
              chartView === 'more'
              ? <div className={styles['multi-chart']}>
                {
                  chartData.map((item, i) => {
                    return <div key={i} className={styles['chart-item']}>
                      <HistoryLine
                        chartData={[item]}
                        historyFrom={this.state.historyFrom}
                        historyTo={this.state.historyTo}
                        updateEvents={this.updataTable}
                      />
                    </div>
                  })
                }
              </div>
              : false
            }
            {
              chartView === 'scatter' && scatterXLabel === 'time'
              ? <div className={styles['scatter-chart']}>
                <HistoryLine
                  type='scatter'
                  chartData={this.state.scatterData}
                  historyFrom={this.state.historyFrom}
                  historyTo={this.state.historyTo}
                  updateEvents={this.updataTable}
                />
              </div>
              : false
            }

            {
              chartView === 'scatter' && scatterXLabel !== 'time'
              ? <div className={styles['scatter-chart']}>
                <ScatterHistoryLine
                  {...{
                    field: scatterXLabel,
                    chartData: this.state.scatterData
                  }}
                />
              </div>
              : false
            }
          </TabPane>
        </Tabs>
      </div>
    )
  }
 }

const mapStatesToProps = (state) => {
  return {
    deviceCard: state.deviceCard,
    deviceFileCondition: state.deviceFileCondition
  }
}
export default connect(mapStatesToProps, {
  changeHistoryChartCond, changeDynamicChartCond, changeDynamicDateCond })(Condition)
